<template>
	<view class="container">
		<u-tabs :list="list" :is-scroll="false" :current="current" @change="change" font-size="26"
			inactive-color="#666666" active-color="#40AE36"></u-tabs>
		<view class="content">
			<view class="order" v-for="(item, index) in orderList" :key="item.id">
				<view @click="goDetail(item.id)">
					<view class="order-top">
						<text class="time">{{item.time}}</text>
						<text
							:class="[item.statusText== '待支付' ? 'status-nopay': '', item.statusText=='已支付'? 'status-pay': '',item.statusText=='待收货'? 'status-pay': '',item.statusText=='待评价'? 'status-comment': '',item.statusText=='已取消'? 'status-cancel': '']">{{item.statusText}}</text>
					</view>
					<view class="shopname"></view>
					<view @click="tologistics(item.id)" class="logistics" v-if="item.logistics && item.logistics.length > 0">
						<view class="logistics-left">
							<image src="/static/icon/logistics.png"></image>
							<view class="logistics-info">
								<text class="logistics-address">{{ item.logistics[0].detail }}</text>
								<text class="logistics-time">{{ item.logistics[0].time }}</text>
							</view>
						</view>
						<view class="logistics-right">
							<image src="/static/icon/right.png"></image>
						</view>
					</view>
					<view class="order-middle">
						<view class="image" v-for="carItem in item.cartList">
							<image :src="carItem.product.post_url"></image>
						</view>
						<view class="info">
							<text class="num">共{{item.count}}件</text>
							<text>合计:<text class="price">￥{{item.price}}</text></text>
						</view>
					</view>
				</view>
				<view class="order-bottom">
					<view class="btns">
						<button class="cancel" v-if="item.statusText=='待支付'"
							@click="cancelOrder(item.id)">取消订单</button>
<!--						<button class="cancel" v-if="item.statusText=='待收货' || item.statusText=='待评价'">再来一单</button>-->
						<button class="pay" v-if="item.statusText=='待支付'" @click="goPayment(item.id)">去支付</button>
						<button class="pay" v-if="item.statusText=='已支付'" @click="remind()">提醒发货</button>
						<button class="pay" v-if="item.statusText=='待收货'">确认收货</button>
            <button class="cancel" v-if="item.statusText=='已支付'" @click="refund(item.id)">退款/售后</button>
<!--            <button class="cancel" v-if="item.statusText!=='待支付' && item.statusText!=='退款中'&& item.statusText!=='已取消'" @click="refund(item.id)">退款/售后</button>-->
						<button class="pay" v-if="item.statusText=='已完成' && !item.comments" @click="goComment(item.id)">去评价</button>
					</view>
				</view>
			</view>

			<!-- 内容为空 -->
			<view class="empty" v-if="orderList.length == 0">
				<u-empty text="抱歉，没有订单数据" mode="order"></u-empty>
			</view>
		</view>

    <!-- 退款弹窗 -->
    <u-popup v-model="showRefundPopup" mode="bottom" border-radius="16">
      <view class="refund-popup">
        <view class="popup-title">申请退款</view>
        <view class="refund-form">
          <view class="form-item">
            <view class="form-label">退款原因</view>
            <textarea class="refund-remark" v-model="refundReason" placeholder="请输入退款说明（选填）" maxlength="200"></textarea>
            <view class="char-count">{{ refundReason.length }}/200</view>
          </view>
        </view>
        <view class="popup-buttons" style="padding-bottom: 20rpx">
          <button class="popup-btn cancel" @click="showRefundPopup = false">取消</button>
          <button class="popup-btn confirm" @click="submitRefund">确认退款</button>
        </view>
      </view>
    </u-popup>
	</view>
</template>

<script>
	import {ORDER_STATUS_TEXT, ORDER_STATUS} from "../../utils/enum";

  export default {
		data() {
			return {
				list: [{
					name: '全部'
				}, {
					name: '待支付'
				}, {
					name: '已支付',
				}, {
					name: '待收货',
				},{
          name: '退款中',
        }, {
          name: '已完成',
        }, {
          name: '已取消',
        }
        ],
				current: 0,
				orderList: [],
				loading: false,
        showRefundPopup: false,
        refundOrderId: '',
        refundReason: '',
			};
		},
		onShow() {
			this.getData();
		},
		methods: {
			// 数据初始化
			getData() {
				// 根据当前选中的tab获取对应状态的订单
				let status = '';
				if (this.current === 1) {
					status = ORDER_STATUS.PENDING; // 待支付
				} else if (this.current === 2) {
					status = ORDER_STATUS.PAID; // 已支付
				} else if (this.current === 3) {
					status = ORDER_STATUS.SHIPPED; // 待收货
				} else if (this.current === 4) {
					status = ORDER_STATUS.REFUNDING; // 退款中
				} else if (this.current === 5) {
          status = ORDER_STATUS.COMPLETED; // 已完成
        } else if (this.current === 6) {
          status = ORDER_STATUS.CANCELLED; // 已取消
				}
				if (!this.$store.state.userInfo.id) {
          return
				}
				this.$api.getOrderPage({
					pageNum: 1,
					pageSize: 9999,
					status: status,
          user_id: this.$store.state.userInfo.id
				}).then(res => {
					if (res.rows && res.rows.length > 0) {
						// 格式化订单数据
						this.orderList = res.rows.map(item => {
              let cartList = []
              if (item.items && item.items.length) {
                cartList = item.items.slice(0,2).map(item => {
                  let cartItem = {}
                  if (item.product_detail) {
                    cartItem = JSON.parse(item.product_detail)
                  }
                  return {
                    ...cartItem,
                  }
                }).filter(item => item.id)
              }
							return {
                ...item,
								id: item.id,
								time:item.create_time,
								status: item.status,
                statusText: ORDER_STATUS_TEXT[item.status],
								count: item.count, // 这里可以根据实际订单商品数量修改
								price: item.payment_amount || item.amount,
                cartList,
                comments: item.comments.length || 0,
							};
						});
					} else {
						this.orderList = [];
					}
				}).catch(err => {
					console.error('获取订单列表失败', err);
					this.orderList = [];
					this.$utils.toastTip("获取订单列表失败");
				});
			},
			// 切换订单状态
			change(index) {
				this.current = index;
				// 切换状态后重新获取数据
				this.getData();
			},
			// 跳转订单详情
			goDetail(id) {
				uni.navigateTo({
					url: "/pages/order/detail?orderId=" + id
				})
			},
      tologistics(id) {
        uni.navigateTo({
          url: "/pages/logistics/logistics?orderId=" + id
        })
      },
			// 跳转去评价页面
			goComment(orderId) {
				uni.navigateTo({
					url: "/pages/order/comment?orderId=" + orderId
				})
			},
			// // 跳转去支付页面
			// goPayment() {
			// 	uni.navigateTo({
			// 		url: "/pages/cart/payment"
			// 	})
			// },
      goPayment(order_id){
        uni.showLoading({
          title:'微信支付请求'
        });
        const that = this
        this.$api.createPay({
          order_id
        }).then(payment =>{
          uni.requestPayment({
            provider: 'wxpay',
            timeStamp: payment.timestamp,
            nonceStr: payment.nonce_str,
            package: payment.package,
            signType: payment.signType,
            paySign: payment.paySign,
            success:(result)=> {
              uni.showToast({
                title:'支付成功'
              });
            },
            fail: (result) => {
              console.log('result,失败啦',result)
              uni.showToast({
                icon:'none',
                title:'支付失败',
              });
            },
            complete: () => {
              setTimeout(() => {
                uni.navigateTo({
                  url: "/pages/cart/paymentinfo?orderId=" + order_id
                })
              }, 1000);
            }
          });
        }).catch(res=>{
          this.loading = false;
          setTimeout(() => {
            uni.navigateTo({
              url: "/pages/cart/paymentinfo?orderId=" + order_id
            })
          }, 1000);
        })
      },
			// 提醒发货
			remind() {
				this.$utils.toastTip("已向商家发送发货提醒");
			},
      // 退款
      refund(orderId) {
        if (!orderId) {
          this.$utils.toastTip("订单ID不能为空");
          return;
        }
        this.showRefundPopup = true
        this.refundOrderId = orderId
      },
      submitRefund() {
        if (!this.refundReason) {
          this.$utils.toastTip("退款原因不能为空");
          return;
        }
        this.$api.refundOrder({
          id: this.refundOrderId,
          refund_reason: this.refundReason,
        }).then(res => {
          this.$utils.toastTip("退款申请提交成功");
          this.showRefundPopup = false
          // 刷新订单列表
          this.getData();
        })
      },
			// 取消订单
			cancelOrder(orderId) {
				if (!orderId) {
					this.$utils.toastTip("订单ID不能为空");
					return;
				}

				this.$utils.showConfirm("确定要取消订单吗？").then(res => {
					if (res.confirm) {
						// 调用取消订单API
						this.$api.cancelOrder({
							id: orderId
						}).then(res => {
							this.$utils.toastTip("取消成功！");
							// 刷新订单列表
							this.getData();
						}).catch(err => {
							console.error('取消订单失败', err);
							this.$utils.toastTip("取消订单失败: " + (err.message || '未知错误'));
						});
					}
				});
			}
		}
	}
</script>

<style>
	page {
		background: #F8F9FA;
	}
</style>

<style lang="scss" scoped>
	.container {
		margin: 0;
		display: flex;
		flex-direction: column;
	}

	.content {
		padding: 30rpx;
	}
  /* 退款弹窗 */
  .refund-popup {
    padding: 30rpx;
  }

  .popup-title {
    font-size: 32rpx;
    font-weight: bold;
    text-align: center;
    margin-bottom: 30rpx;
  }

  .refund-form {
    margin-bottom: 30rpx;
  }

  .form-item {
    margin-bottom: 20rpx;
  }

  .form-label {
    font-size: 28rpx;
    color: #333;
    margin-bottom: 16rpx;
  }

  .refund-remark {
    width: 100%;
    height: 200rpx;
    background-color: #f5f5f5;
    border-radius: 8rpx;
    padding: 20rpx;
    font-size: 28rpx;
    box-sizing: border-box;
  }

  .char-count {
    text-align: right;
    font-size: 24rpx;
    color: #999;
    margin-top: 10rpx;
  }

  .popup-buttons {
    display: flex;
    justify-content: space-between;
  }

  .popup-btn {
    flex: 1;
    height: 80rpx;
    line-height: 80rpx;
    text-align: center;
    border-radius: 40rpx;
    font-size: 28rpx;
    margin: 0 10rpx;
  }

  .popup-btn.cancel {
    background-color: #f5f5f5;
    color: #666;
  }

  .popup-btn.confirm {
    background-color: #40AE36;
    color: #fff;
  }
	.order {
		border-radius: 20rpx;
		background: #FFFFFF;
		padding: 24rpx 30rpx 30rpx 30rpx;
		margin-bottom: 22rpx;

		.order-top {
			display: flex;
			align-items: center;
			justify-content: space-between;
			border-bottom: 1rpx solid #ECECEC;
			padding-bottom: 22rpx;

			.time {
				font-size: 26rpx;
				color: #999999;
			}

			.status-nopay {
				font-size: 26rpx;
				color: #F55726;
			}

			.status-pay {
				font-size: 26rpx;
				color: #26ACF5;
			}

			.status-comment {
				font-size: 26rpx;
				color: #40AE36;
			}

			.status-cancel {
				font-size: 26rpx;
				color: #999999;
			}
		}

		.shopname {
			font-size: 26rpx;
			color: #333333;
			margin: 20rpx 0rpx;
		}

		.logistics {
			border-radius: 20rpx;
			background: #F8F9FA;
			display: flex;
			align-items: center;
			justify-content: space-between;
			margin: 20rpx 0rpx;
			padding: 20rpx;

			.logistics-left {
				display: flex;
				align-items: center;

				image {
					width: 48rpx;
					height: 48rpx;
				}

				.logistics-info {
					display: flex;
					flex-direction: column;
					margin-left: 20rpx;
					line-height: 40rpx;

					.logistics-address {
						font-size: 24rpx;
						color: #333333;
					}

					.logistics-time {
						font-size: 22rpx;
						color: #999393;
					}
				}
			}

			.logistics-right {
				image {
					width: 48rpx;
					height: 48rpx;
				}
			}
		}

		.order-middle {
			display: flex;
			align-items: flex-end;
			justify-content: space-between;

			.info {
				display: flex;
				flex-direction: column;
				align-items: flex-end;
				font-size: 22rpx;
				color: #333333;

				.num {
					font-size: 22rpx;
					color: #999999;
					margin-bottom: 6rpx;
				}

				.price {
					font-size: 32rpx;
					font-weight: 600;
					color: #333333;
				}
			}

			image {
				width: 130rpx;
				height: 130rpx;
				border-radius: 10rpx;
				margin-right: 20rpx;
			}
		}

		.order-bottom {
			margin-top: 30rpx;

			.btns {
				display: flex;
				justify-content: flex-end;

				button {
					border-radius: 24rpx;
					background-color: #FFFFFF;
					margin: 0;
				}

				button::after {
					border: none;
				}

				.cancel {
					font-size: 24rpx;
					color: #333333;
					border: 1rpx solid #999999;
				}

				.pay {
					font-size: 24rpx;
					color: #40AE36;
					border: 1rpx solid #40AE36;
          margin: 0 16rpx;
				}
			}

		}
	}

	.empty {
		margin-top: 200rpx;
	}
</style>
